package com.terracloud.server.controller;

import com.terracloud.server.common.data.Role;
import com.terracloud.server.common.data.exception.ThingsboardException;
import com.terracloud.server.common.data.id.TenantId;
import com.terracloud.server.common.data.page.PageData;
import com.terracloud.server.service.entitiy.role.RoleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

/**
 *
 * @author chenhainan
 * @since 2025/10/20
 */
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
@Slf4j
public class RoleController extends BaseController {

    private final RoleService roleService;

    @GetMapping("/roles")
    @PreAuthorize("hasAuthority('TENANT_ADMIN')")
    public PageData<Role> getRoles(@RequestParam int pageSize,
                                   @RequestParam int page,
                                   @RequestParam(required = false) String textSearch) throws ThingsboardException {
        TenantId tenantId = getCurrentUser().getTenantId();
        return roleService.getRoles(tenantId, page, pageSize, textSearch);
    }

    @PostMapping("/role")
    @PreAuthorize("hasAuthority('TENANT_ADMIN')")
    public Role saveRole(@RequestBody Role role) throws ThingsboardException {
        return roleService.saveRole(role, getCurrentUser());
    }

    @GetMapping("/role/{roleId}")
    @PreAuthorize("hasAuthority('TENANT_ADMIN')")
    public Role getRoleInfo(@PathVariable String roleId) throws ThingsboardException {
        return roleService.getRoleInfo(getCurrentUser(), UUID.fromString(roleId));
    }

    @DeleteMapping("/role/{roleId}")
    @PreAuthorize("hasAuthority('TENANT_ADMIN')")
    public void deleteRole(@PathVariable String roleId) throws ThingsboardException {
        roleService.deleteRole(getCurrentUser(), UUID.fromString(roleId));
    }
}
